package com.shixj.easy.spider.factory;

import com.shixj.easy.spider.constant.IllegalContants;
import com.shixj.easy.spider.model.Chapter;
import com.shixj.easy.spider.model.RegexConfig;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shixj on 2018/1/15.
 */
public interface BaseFactory {
    /**
     * 获取元素text
     *
     * @param document
     * @param regex
     * @return
     */
    default String getPartText(Document document, String regex) {
        return IllegalContants.replaceIllegalWords(document.select(regex).first().text());
    }

    /**
     * 获取元素html
     *
     * @param document
     * @param regex
     * @return
     */
    default String getPartHtml(Document document, String regex) {
        return IllegalContants.replaceIllegalWords(document.select(regex).first().html());
    }

    /**
     * 获取章节列表
     *
     * @param document
     * @param regexConfig
     * @return
     */
    default List<Chapter> getCatalog(Document document, RegexConfig regexConfig) {
        List<Chapter> chapters=new ArrayList<>();
        //dl dd
        Elements elements=document.select(regexConfig.getCatalogRegex());
        for(Element element:elements){
            Chapter chapter=new Chapter();
            chapter.setTitle(element.text());
            chapter.setSourceId(regexConfig.getBaseUrl()+element.attr("href"));
            chapters.add(chapter);
        }
        return chapters;
    }
}
